package com.zzvcom.webapp.action.web;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zzvcom.persist.model.user.User;
import com.zzvcom.service.UserManager;
import com.zzvcom.utils.ServiceUtil;

@Controller
@Scope("prototype")
public class LoginAction
{

	private UserManager manager;

	private String username;

	private String password;

	private String code;

	private String error = "sorry your inputs is wrong!";

	public String execute()
	{
		if (StringUtils.isNotBlank(username)
				&& StringUtils.isNotBlank(password)
				&& StringUtils.isNotBlank(code))
		{
			Object rand = ServiceUtil.getSessionValue("rand");		
			if (rand!=null && rand.equals(code))
			{
				DetachedCriteria dc = DetachedCriteria.forClass(User.class);
				dc.add(Restrictions.eq("username", username));
				dc.add(Restrictions.eq("password", password));
				List<User>rs=manager.getListByDetachedCriteria(dc);
				if (rs.size() > 0)
				{
					ServiceUtil.setSessionValue("user", rs.get(0));
					return "admin";
				}
			}
		} else
		{
			error = "some field is omit!";
		}

		return "login";
	}

	public String getError()
	{
		return error;
	}

	public void setError(String error)
	{
		this.error = error;
	}

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public String getCode()
	{
		return code;
	}

	public void setCode(String code)
	{
		this.code = code;
	}

	public UserManager getManager()
	{
		return manager;
	}

	@Autowired
	public void setManager(UserManager manager)
	{
		this.manager = manager;
	}

}
